<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref,computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import {
  addStudentService,
  updateStudentService,
  getStudentByIdService
} from '../../api/student'

import { getStuByClassIdService, deleteScByStuIdService } from '../../api/sc'
import { getByIdService } from '../../api/course'

const route = useRoute();
const students = ref([])
const filteredStudents = ref([]) // 存储过滤后的学生列表
const title = ref('')
const dialogVisible = ref(false)
const studentModel = ref({
  username: '',
  name: '',
  email: '',
  phone: '',
  college: '',
  yearOfStudy: '',
  id: 0,
})
const searchQuery = ref('')
const select = ref('') // 默认搜索选项
const courseName = ref('')

// 显示学生列表信息
const studentList = async () => {
  const couId = computed(() => route.query.couId);
  const ces = await getByIdService(couId.value); // 获取课程名称
  courseName.value = ces.data.name;
  const les = await getStuByClassIdService(couId.value); // 获取课程内的学生
  const studentIds = les.data.map(item => item.stuId); // 获取学生id
  students.value = []; 
  for (const studentId of studentIds) {
    const res = await getStudentByIdService(studentId); // 获取单个学生信息
    if (res.data) {
      students.value.push(res.data); // 将获取的学生信息推入学生列表
    }
  }
  filteredStudents.value = [...students.value]; // 初始化过滤后的学生列表
}

// 执行搜索的方法
const performSearch = () => {
  if (!searchQuery.value) {
    filteredStudents.value = [...students.value];
    return;
  }

  filteredStudents.value = students.value.filter(student => {
    switch (select.value) {
      case 'name':
        return student.name.includes(searchQuery.value);
      case 'college':
        return student.college.includes(searchQuery.value);
      default:
        return false;
    }
  });
}

// 添加学生弹窗
const addStudent = async () => {
  let res = await addStudentService(studentModel.value)
  if (res) {
    ElMessage.success(res.message ? res.message : '添加成功')
    studentList()
    dialogVisible.value = false
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，添加失败了')
  }
}

// 清空表单数据
const clearForm = () => {
  studentModel.value = {
    username: '',
    name: '',
    email: '',
    phone: '',
    college: '',
    yearOfStudy:'',
    id: 0,
  }
  title.value = '添加学生'
  dialogVisible.value = true
}

// 显示学生的信息到编辑弹窗
const showStudent = (row) => {
  title.value = '编辑学生'
  studentModel.value = { ...row }
  dialogVisible.value = true
}

// 编辑学生
const editStudent = async () => {
  let res = await updateStudentService(studentModel.value)
  if (res) {
    ElMessage.success(res.message ? res.message : '修改成功')
    studentList()
    dialogVisible.value = false
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，修改失败了')
  }
}

// 删除学生
const deleteStudent = async (id) => {
  ElMessageBox.confirm('您确定要删除这个学生吗?', '注意', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const couId = computed(() => route.query.couId);
    const res = await deleteScByStuIdService(id,couId.value)
    if (res) {
      ElMessage.success(res.message ? res.message : '删除成功')
      studentList()
    } else {
      ElMessage.error(res.message ? res.message : '很可惜，删除失败了')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
const goBack = () => {
  window.history.back(); // 或者使用路由实例进行导航
}
studentList()
</script>

<template>
  <el-card class="page-container">
    <template #header>
  <div class="header">
    <!-- <span>{{ courseName }}</span> -->
    <el-button @click="goBack" type="primary" >返回</el-button>
    <div class="mt-4">
          <el-input
            v-model="searchQuery"
            style="max-width: 600px"
            placeholder="请输入关键词"
            class="input-with-select"
          >
            <template #prepend>
              <el-select v-model="select" placeholder="选择搜索类型" style="width: 115px">
                <el-option label="学生姓名" value="name" />
                <el-option label="学院" value="college" />
              </el-select>
            </template>
            <template #append>
              <el-button @click="performSearch()">搜索</el-button>
            </template>
          </el-input>
        </div>
    <div class="extra">
      <el-button @click="clearForm" type="primary">添加学生</el-button>
    </div>
  </div>
</template>


    <!-- 添加学生弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="50%">
      <el-transfer :model="studentModel" :data="students" />
      <!-- <el-form :model="studentModel" :rules="rules" label-width="100px" style="padding-right: 30px">
        <el-form-item label="学生用户" prop="username">
          <el-input v-model="studentModel.username" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="studentModel.name" minlength="2" maxlength="6"></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="college">
          <el-input v-model="studentModel.college"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="yearOfStudy">
          <el-input v-model="studentModel.yearOfStudy"></el-input>
        </el-form-item>
      </el-form> -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title == '添加学生' ? addStudent() : editStudent()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 列表 -->
    <el-table :data="filteredStudents" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"> </el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="学院" prop="college"></el-table-column>
      <el-table-column label="年级" prop="yearOfStudy"></el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="success" plain @click="showStudent(row)">查看详情</el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteStudent(row.id)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
